package com.example.springboottestservice.aop;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLIBProxyTest {

    public static void test(){

        //TestCGLIBProxyService testCGLIBProxyService = new TestCGLIBProxyService();

        TestCGLIBProxyService proxy = (TestCGLIBProxyService)TestCGLIBProxyFactory.getProxy(TestCGLIBProxyService.class);

        proxy.proxyMethod("aaa");
    }

}

class TestCGLIBProxyFactory{
    public static Object getProxy(Class<?> clazz) {
        // 创建动态代理增强类
        Enhancer enhancer = new Enhancer();
        // 设置类加载器
        enhancer.setClassLoader(clazz.getClassLoader());
        // 设置被代理类
        enhancer.setSuperclass(clazz);
        // 设置方法拦截器
        enhancer.setCallback(new TestCGLIBProxyMethodInterceptor());
        // 创建代理类
        return enhancer.create();
    }
}

class TestCGLIBProxyService{
    public String proxyMethod(String a) {
        System.out.println("执行proxyMethod....");
        return a;
    }
}

class TestCGLIBProxyMethodInterceptor implements MethodInterceptor {


    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        //调用方法之前，我们可以添加自己的操作
        System.out.println("before method " + method.getName());
        Object object = methodProxy.invokeSuper(o, args);
        //调用方法之后，我们同样可以添加自己的操作
        System.out.println("after method " + method.getName());
        return object;
    }
}


